﻿/// <reference path="../../extjs/ext-all-debug.js" />
Ext.define('yzmh.controller.Collects', {
    extend: 'Ext.app.Controller',

    stores: ['collect.Bengou', 'collect.Xemh', 'collect.Xindm', 'collect.52tian', 'collect.Manhuazhu', 'collect.Hhcomic', 'collect.Mkzhan', 'collect.U17', 'collect.Jmydm'],

    models: ['Collect'],

    views: ['collect.ChapterImport', 'collect.Bengou', 'collect.Xemh', 'collect.Xindm', 'collect.52tian', 'collect.Manhuazhu', 'collect.Hhcomic', 'collect.Mkzhan', 'collect.U17', 'collect.Jmydm'],

    refs: [{
        ref: 'bengou',
        selector: 'bengou'
    }, {
        ref: 'xemh',
        selector: 'xemh'
    }, {
        ref: 'xindm',
        selector: 'xindm'
    }, {
        ref: '52tian',
        selector: '52tian'
    }, {
        ref: 'manhuazhu',
        selector: 'manhuazhu'
    }, {
        ref: 'hhcomic',
        selector: 'hhcomic'
    }, {
        ref: 'mkzhan',
        selector: 'mkzhan'
    }, {
        ref: 'u17',
        selector: 'u17'
    }, {
        ref: 'jmydm',
        selector: 'jmydm'
    }, {
        ref: 'chapterImport',
        selector: 'chapterimport'
    }, {
        ref: 'progressbar',
        selector: 'xindm > grid progressbar'
    }],

    init: function () {
        this.control({
            'bengou > grid': {
                render: this.loadBengouList
            },
            'xemh > grid': {
                render: this.loadXemhList
            },
            'xindm > grid': {
                render: this.loadXindmList
            },
            '52tian > grid': {
                render: this.load52tianList
            },
            'manhuazhu > grid': {
                render: this.loadManhuazhuList
            },
            'hhcomic > grid': {
                render: this.loadHhcomicList
            },
            'mkzhan > grid': {
                render: this.loadMkzhanList
            },
            'u17 > grid': {
                render: this.loadU17List
            },
            'jmydm > grid': {
                render: this.loadJmydmList
            },
            'bengou > grid,xemh > grid,52tian > grid,manhuazhu > grid,hhcomic > grid,mkzhan > grid,u17 > grid,jmydm > grid,xindm > grid': {
                itemdblclick: this.showSingle
            },
            'bengou grid[name=chaptergrid]': {
                itemclick: function () { this.getBengou().down("button[action=importChapter]").enable(); }
            },
            'xemh grid[name=chaptergrid]': {
                itemclick: function () { this.getXemh().down("button[action=importChapter]").enable(); }
            },
            '52tian grid[name=chaptergrid]': {
                itemclick: function () { this.get52tian().down("button[action=importChapter]").enable(); }
            },
            'manhuazhu grid[name=chaptergrid]': {
                itemclick: function () { this.getManhuazhu().down("button[action=importChapter]").enable(); }
            },
            'hhcomic grid[name=chaptergrid]': {
                itemclick: function () { this.getHhcomic().down("button[action=importChapter]").enable(); }
            },
            'xindm grid[name=chaptergrid]': {
                itemclick: function () { this.getXindm().down("button[action=importChapter]").enable(); }
            },
            'mkzhan grid[name=chaptergrid]': {
                itemclick: function () { this.getMkzhan().down("button[action=importChapter]").enable(); }
            },
            'u17 grid[name=chaptergrid]': {
                itemclick: function () { this.getU17().down("button[action=importChapter]").enable(); }
            },
            'jmydm grid[name=chaptergrid]': {
                itemclick: function () { this.getJmydm().down("button[action=importChapter]").enable(); }
            },
            'bengou > grid actioncolumn[action=view],xemh > grid actioncolumn[action=view],xindm > grid actioncolumn[action=view],52tian > grid actioncolumn[action=view],manhuazhu > grid actioncolumn[action=view],hhcomic > grid actioncolumn[action=view],mkzhan > grid actioncolumn[action=view],u17 > grid actioncolumn[action=view],jmydm > grid actioncolumn[action=view]': {
                click: this.viewComic
            },
            'bengou combo': {
                select: function () {
                    var params = {};
                    Ext.each(arguments[0].up('toolbar').query('combo'), function (combo) {
                        params[combo.getName()] = (combo.getValue() == null || combo.getValue() == '全部') ? '' : combo.getValue();
                    });
                    this.getCollectBengouStore().proxy.extraParams = params;
                    this.getCollectBengouStore().load();
                }
            },
            'xemh combo': {
                select: function () {
                    var params = {};
                    Ext.each(arguments[0].up('toolbar').query('combo'), function (combo) {
                        params[combo.getName()] = combo.getValue();
                    });
                    this.getCollectXemhStore().proxy.extraParams = params;
                    this.getCollectXemhStore().load();
                }
            },
            'mkzhan combo': {
                select: function () {
                    var params = {};
                    Ext.each(arguments[0].up('toolbar').query('combo'), function (combo) {
                        params[combo.getName()] = combo.getValue();
                    });
                    this.getCollectMkzhanStore().proxy.extraParams = params;
                    this.getCollectMkzhanStore().load();
                }
            },
            'u17 combo': {
                select: function () {
                    var params = {};
                    Ext.each(arguments[0].up('toolbar').query('combo'), function (combo) {
                        params[combo.getName()] = combo.getValue();
                    });
                    this.getCollectU17Store().proxy.extraParams = params;
                    this.getCollectU17Store().load();
                }
            },
            'jmydm combo': {
                select: function () {
                    var params = {};
                    Ext.each(arguments[0].up('toolbar').query('combo'), function (combo) {
                        params[combo.getName()] = combo.getValue();
                    });
                    this.getCollectJmydmStore().proxy.extraParams = params;
                    this.getCollectJmydmStore().load();
                }
            },
            'xindm combo': {
                select: function () {
                    var params = {};
                    Ext.each(arguments[0].up('toolbar').query('combo'), function (combo) {
                        params[combo.getName()] = (combo.getValue() == null || combo.getValue() == '全部') ? '' : combo.getValue();
                    });
                    this.getCollectXindmStore().proxy.extraParams = params;
                    this.getCollectXindmStore().load();
                }
            },
            'bengou button[action=importComic],xemh button[action=importComic],52tian button[action=importComic],manhuazhu button[action=importComic],hhcomic button[action=importComic],mkzhan button[action=importComic],u17 button[action=importComic],jmydm button[action=importComic]': {
                click: this.importComic
            },
            'bengou button[action=checkComic],xemh button[action=checkComic],52tian button[action=checkComic],manhuazhu button[action=checkComic],hhcomic button[action=checkComic],mkzhan button[action=checkComic],u17 button[action=checkComic],jmydm button[action=checkComic],xindm button[action=checkComic]': {
                click: this.checkComic
            },
            'bengou button[action=importChapter],xemh button[action=importChapter],52tian button[action=importChapter],manhuazhu button[action=importChapter],hhcomic button[action=importChapter],mkzhan button[action=importChapter],u17 button[action=importChapter],jmydm button[action=importChapter],xindm button[action=importChapter]': {
                click: this.importChapters
            },
            'chapterimport button[action=save]': {
                click: this.saveChapters
            },
            'chapterimport form boxselect': {
                select: this.comicNameSelect
            },
            'xindm button[action=importComic]': {
                click: this.syncXindmComics
            },
            'jmydm checkcode': {
                change:function( obj, newValue, oldValue, eOpts ){
                    this.getCollectJmydmStore().proxy.extraParams = {
                        code:  newValue
                    };
                }
            }
        });
    },

    comicNameSelect: function (combo) {
        var form = combo.up('form');
        form.mask();
        Ext.Ajax.request({
            url: 'data/chapter.aspx?a=gettpadd',
            params: { cid: combo.getValue() },
            method: 'POST',
            success: function (response, opts) {
                form.unmask();
                var result = Ext.decode(response.responseText);
                if (result.success) {
                    form.down('textfield[name=tpadd]').setValue(result.value);
                } else {
                    notification("错误", result.errorMessage, true);
                }
            }
        });
        form.down('combo[name=zjid]').setValue("");
        form.down('combo[name=zjid]').getStore().proxy.extraParams = { cid: combo.getValue() };
        form.down('combo[name=zjid]').getStore().reload();
    },

    importComic: function (button) {
        var edit = Ext.create('yzmh.view.comic.Edit').show();
        var data = button.up('panel').down('propertygrid').source;
        for (var i in data) {
            if (edit.down('form').getForm().findField(i) != null) {
                edit.down('form').getForm().findField(i).setValue(data[i]);
            }
        }
    },

    saveChapters: function (button) {
        var win = button.up('window'),
        form = win.down('form');
        if (form.getForm().isValid()) {
            form.submit({
                clientValidation: true,
                waitMsg: '正在提交数据...',
                url: 'data/collect/' + form.getForm().getValues().action + '.aspx?a=import',
                params: { mhmc: form.getForm().findField("id").getRawValue() },
                success: function (form, action) {
                    win.close();
                },
                failure: function (form, action) {
                    Ext.Msg.alert('Failed', action.result ? action.result.errorMessage : 'No response');
                }
            });
        }
    },

    importChapters: function (button) {
        var panel = button.up('panel');
        var rows = panel.down("grid[name=chaptergrid]").getSelectionModel().getSelection();
        var pgrid = panel.down('propertygrid');
        if (rows.length > 0) {
            var zjurl = [];
            Ext.each(rows, function (row) {
                zjurl.push(row.get("zjurl"));
            });
            var edit = Ext.create('yzmh.view.collect.ChapterImport').show();
            edit.down('form').getForm().findField("id").getStore().load({ params: { mhmc: pgrid.source.mhmc } });
            edit.down('form').getForm().findField("action").setValue(panel.getXType());
            edit.down('form').getForm().findField("zjurl").setValue(zjurl.join('\n'));
            edit.down('form').getForm().findField("tpadd").setValue(pgrid.source.zm + "/" + pgrid.source.mhmc + "/");
            if (rows.length > 1) {
                edit.down('form').getForm().findField("zjid").hide();
            } 
        }
    },

    checkComic:function(button){
        var grid = button.up('panel').down('grid'), mhmcArr = [];
        grid.mask();
        grid.getStore().each(function (row) {
            mhmcArr.push(row.get('mhmc'))
        });
        if (mhmcArr.length > 0) {
            Ext.Ajax.request({
                url: 'data/comics.aspx?a=check',
                params: { mhmc: mhmcArr.join('^') },
                method: 'POST',
                success: function (response, opts) {
                    grid.unmask();
                    var result = Ext.decode(response.responseText);
                    if (result.success) {
                        Ext.each(result.data, function (obj) {
                            grid.getStore().getById(obj.mhmc).set("exist", obj.exist);
                        });
                    } else {
                        Ext.Msg.alert("错误", result.errorMessage);
                    }
                }
            });
        }
    },

    loadBengouList: function (panel) {
        this.getCollectBengouStore().filters.clear();
        panel.up('panel').down("toolbar").insert(0, {
            store: this.getCollectBengouStore(),
            xtype: 'searchfield',
            width: 220
        });
        this.getCollectBengouStore().load();
    },

    loadXemhList: function (panel) {
        this.getCollectXemhStore().filters.clear();
        panel.up('panel').down('toolbar').insert(0, {
            store: this.getCollectXemhStore(),
            xtype: 'searchfield',
            width: 220
        });
        this.getCollectXemhStore().load();
    },

    loadXindmList: function (panel) {
        this.getCollectXindmStore().load();
    },

    load52tianList: function (panel) {
        this.getCollect52tianStore().filters.clear();
        panel.up('panel').down("toolbar").insert(0, {
            store: this.getCollect52tianStore(),
            xtype: 'searchfield',
            width: 220
        });
        this.getCollect52tianStore().guaranteeRange(0, 49);
    },

    loadManhuazhuList: function (panel) {
        this.getCollectManhuazhuStore().filters.clear();
        panel.up('panel').down("toolbar").insert(0, {
            store: this.getCollectManhuazhuStore(),
            xtype: 'searchfield',
            width: 220
        });
        this.getCollectManhuazhuStore().load();
    },

    loadHhcomicList: function (panel) {
        this.getCollectHhcomicStore().filters.clear();
        panel.up('panel').down("toolbar").insert(0, {
            store: this.getCollectHhcomicStore(),
            xtype: 'searchfield',
            width: 220
        });
        this.getCollectHhcomicStore().load();
    },

    loadMkzhanList: function (panel) {
        this.getCollectMkzhanStore().filters.clear();
        panel.up('panel').down("toolbar").insert(0, {
            store: this.getCollectMkzhanStore(),
            xtype: 'searchfield',
            width: 100
        });
        this.getCollectMkzhanStore().load();
    },

    loadU17List: function (panel) {
        this.getCollectU17Store().filters.clear();
        panel.up('panel').down("toolbar").insert(0, {
            store: this.getCollectU17Store(),
            xtype: 'searchfield',
            width: 150
        });
        this.getCollectU17Store().load();
    },

    loadJmydmList: function (panel) {
        this.getCollectJmydmStore().filters.clear();
        panel.up('panel').down("toolbar").insert(1, {
            store: this.getCollectJmydmStore(),
            xtype: 'searchfield',
            width: 150
        });
        this.getCollectJmydmStore().load();
    },

    viewComic: function (o, item, rowIndex, colIndex, e, row) {
        window.open(row.get("mhurl"));
    },

    showSingle: function (grid, record) {
        var panel = grid.up("panel").up("panel");
        panel.down("button[action=importChapter]").disable();
        panel.items.getAt(1).show();
        panel.mask();
        Ext.Ajax.request({
            url: 'data/collect/' + panel.xtype+ '.aspx?a=single',
            params: { url: arguments[1].get("mhurl") },
            method: 'POST',
            success: function (response, opts) {
                var result = Ext.decode(response.responseText);
                panel.unmask();
                if (result.success != false) {
                    panel.down("propertygrid").setSource(result);
                    panel.down("grid[name=chaptergrid]").getStore().loadData(result.chapters);
                } else {
                    notification("错误", result.errorMessage, true);
                }
            }
        });
    },

    syncXindmComics: function (button) {
        var rows = this.getXindm().down("grid").getSelectionModel().getSelection();
        var pbar = this.getProgressbar();
        if (rows.length > 0) {
            var v = 0;
            function importComic(record) {
                Ext.Ajax.request({
                    url: 'data/collect/xindm.aspx?a=sync',
                    params: { mhurl: record.get("mhurl") },
                    method: 'POST',
                    success: function (response, opts) {
                        var result = Ext.decode(response.responseText);
                        if (result.success) {
                            v++;
                            pbar.updateProgress(v / rows.length, '正在导入漫画 ' + v + ' / ' + rows.length + '...');
                            if (rows[v] != null) {
                                importComic(rows[v]);
                            } else {
                                pbar.updateText('导入漫画完成')
                            }
                        } else {
                            Ext.Msg.alert("错误", rows[v].get('mhmc') + result.errorMessage);
                        }
                    }
                });
            }
            Ext.Msg.confirm("提示", "确定要导入选中的" + rows.length + "部漫画吗？", function (result) {
                if (result == "yes") {
                    pbar.reset();
                    pbar.show();
                    importComic(rows[v])
                }
            });
        }
    }
});
